<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <!-- 添加角色按钮 -->
            <el-row>
              <el-col>
                <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
              </el-col>
            </el-row>
            <!-- 角色列表区域 -->
            <el-table :data="roleList" border stripe>
                <!-- 展开列 -->
              <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom',i1 == 0 ? 'bdtop':'','vcenter','vrow']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                            <!-- 渲染一级权限 24列 一级用5列-->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级三级权限 -->
                            <el-col :span="19">
                                <el-row :class="[i2 == 0 ? '':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                                    <!-- 通过 for循环 渲染二级标签 -->
                                  <el-col :span="6">
                                        <!-- 二级标签 -->
                                        <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                  </el-col>
                                  <el-col :span="18">
                                    <!-- 三级标签 -->
                                     <el-tag closable @close="removeRightById(scope.row,item3.id)" v-for="(item3,i3) in item2.children" :key="item3.id" type="warning">
                                            {{item3.authName}}
                                    </el-tag>
                                  </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                        <!-- <pre>
                            {{scope.row}}
                        </pre> -->
                    </template>
              </el-table-column>
              <el-table-column label="#" type="index"></el-table-column>
              <el-table-column label="角色名称" prop="roleName"></el-table-column>
              <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
              <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button  size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)">编辑</el-button>
                    <el-button  size="mini" type="danger" icon="el-icon-delete" @click="removeRolesById(scope.row.id)">删除</el-button>
                    <el-button  size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                  </template>
              </el-table-column>
            </el-table>
        </el-card>
        <!-- 添加角色对话框 -->
        <el-dialog title="添加角色" :visible.sync="addDialogVisible" @close="addDialogClosed">
        <el-form :model="addRolesForm" :rules="addFormRules" ref="addRolesRef" label-width="80px">
            <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRolesForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRolesForm.roleDesc"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addRolesUser">确 定</el-button>
        </span>
        </el-dialog>
         <!-- 编辑对话框 -->
        <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%">
            <el-form :model="editRolesForm" :rules="editFormRules" ref="editFormRef" label-width="80px" @close="editDialogClosed">
                <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="editRolesForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="editRolesForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editFormInfo">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配权限的对话框 -->
        <el-dialog title="分配权限" :visible.sync="SetRightDialogVisible" width="50%" @close="SetRightDialogVisibleClosed">
            <!-- 树形控件 -->
            <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" :default-expand-all="true" :default-checked-keys="defKeys" ref="treeRef"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="SetRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>   
    </div>
</template>

<script>
export default {
    data() {
        return {
            //所有角色列表数据
            roleList:[],
            // 添加角色对话框的显示和隐藏
            addDialogVisible: false,
            //添加角色
            addRolesForm: {
                roleName: '',
                roleDesc: ''
           },
            //查询到角色列表
            editRolesForm: {},
            // 编辑对话框的显示和隐藏
            editDialogVisible: false,
            //控制分配权限对话框显示和隐藏
            SetRightDialogVisible:false,
            //当前要被分配角色权限的id
            rolesId: '',
            //所有权限的数据
            rightsList: [],
            //树形控件属性绑定对象
            treeProps:{
                label:'authName',
                children:'children'
            },
            //默认选中的节点id值数组
            defKeys:[],
            //添加表单验证规则 :rules  prop=
            addFormRules:{
                roleName:[
                    {
                        required: true,
                        message:'请输入角色名称',
                        trigger:'blur'
                    }
                ],
                roleDesc:[
                    {
                        required: true,
                        message:'请输入角色描述',
                        trigger:'blur'
                    }
                ]
            },
            //修改表单验证规则
            editFormRules:{
                roleName:[
                    {
                        required: true,
                        message:'请输入角色名称',
                        trigger:'blur'
                    }
                ],
                roleDesc:[
                    {
                        required: true,
                        message:'请输入角色描述',
                        trigger:'blur'
                    }
                ]
            },
        }
    },
    created() {
        this.getRolesList()
    },
    methods: {
        //获取所有角色列表
        async getRolesList(){
            const {data:res}  = await this.$http.get('roles')
            if(res.meta.status != 200){
                return this.$message.error('获取角色列表失败')
            }else{
                this.roleList = res.data
            }
        },
        //添加角色方法
        addRolesUser(){
            this.$refs.addRolesRef.validate(async valid=>{
                if(!valid){
                    this.$message.error('添加角色失败')
                }else{
                    //可以发起网络请求
                    const {data:res}  = await this.$http.post('roles',this.addRolesForm)
                    if(res.meta.status != 201){
                        this.$message.error('添加角色失败')
                    }else{
                        this.$message.success('添加角色成功')
                        //隐藏对话框
                        this.addDialogVisible = false
                        this.getRolesList()
                    }
                }
            })
        },
        //展示编辑用户对话框 根据 ID 查询角色
        async showEditDialog(id){
            const {data:res}  = await this.$http.get('roles/'+id)
            if(res.meta.status != 200){
                    this.$message.error('查询角色失败')
            }else{
                this.editRolesForm = res.data
                this.editDialogVisible = true
            }
        },
        //编辑角色列表的方法
        editFormInfo(){
            this.$refs.editFormRef.validate(async valid =>{
                if(!valid) return
                //发起编辑角色的请求
                const {data:res} = await this.$http.put('roles/'+this.editRolesForm.roleId,{
                    roleName: this.editRolesForm.roleName,
                    roleDesc: this.editRolesForm.roleDesc
                })
                if(res.meta.status!= 200){
                    return this.$message.error('更新角色信息失败')
                }else{
                    this.editDialogVisible = false
                    this.getRolesList()
                    return this.$message.success('更新角色信息成功')
                }
            })
        },
        //根据id删除用户
        async removeRolesById(id){
            //弹框询问是否删除
            const confirmResult =  await this.$confirm('此操作将永久删除该用户, 是否确认?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
            if(confirmResult == 'confirm'){
                const {data:res}  =  await this.$http.delete('roles/'+ id)
                if(res.meta.status != 200){
                    this.$message.error('删除用户失败')
                }else{
                    this.$message.success('删除用户成功')
                    this.getRolesList()
                }   
            }
        },
        //展示分配权限的对话框
        async showSetRightDialog(role){
            //获取所有权限数据
            this.rolesId =  role.id
                const {data:res} = await this.$http.get('rights/tree')
                if(res.meta.status != 200) {
                    return this.$message.error('获取用户权限失败')
                }else{
                    //获取的权限数据 保存到data
                    this.rightsList = res.data
                    console.log(this.rightsList)
                    //递归获取三级节点id
                    this.getLeafKeys(role,this.defKeys)
                this.SetRightDialogVisible =true    
                }
            
            
        },
        //监听关闭添加用户对话框事件
        addDialogClosed(){
            //取消后重置表单 @close
            this.$refs.addRolesRef.resetFields()
        },
        //监听修改用户对话框关闭事件
        editDialogClosed(){
        this.$refs.editFormRef.resetFields()
        },
        // 监听分配权限对话框的关闭事件
        SetRightDialogVisibleClosed() {
            //给defKeys 默认选中的节点重新赋值
            this.defKeys = []
        },
        //根据id删除权限
        async removeRightById(role,rightId){
            //弹框提示用户是否删除
            const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).catch(() => {
            this.$message({
                type: 'info',
                message: '已取消删除'
            });          
          });
            if(confirmResult == 'confirm'){
                const {data:res} =await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
                if(res.meta.status != 200){
                    return this.$message.error('删除权限失败')
                }else{
                    // this.getRolesList()
                    role.children = res.data
                }
            }
        },
        //通过递归的形式 获取角色下所有三级权限id
        getLeafKeys(node,arr){
            //如果当前节点不包含children 可以证明是三级节点
            if(!node.children){
                return arr.push(node.id)
            }else{
                //递归方法
                node.children.forEach(item =>
                    this.getLeafKeys(item,arr)
                )
            }
        },
        //点击为角色分配角色
        async allotRights(){
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            // console.log(keys)
            //拼接
            const idStr = keys.join(',')
            const { data: res } = await this.$http.post(`roles/${this.rolesId}/rights`, { rids: idStr })
            if (res.meta.status !== 200) {
            return this.$message.error('分配权限失败!')
            }else{
                this.$message.success('分配权限成功!')
                this.getRolesList()
                this.SetRightDialogVisible = false
            }

        }
    },
}
</script>

<style lang="less" scoped>
    .el-tag{
        margin: 7px;
    }
    .bdtop{
        border-top: 1px solid #eee;
    }
    .bdbottom{
        border-bottom: 1px solid #eee;
    }
    .vcenter{
    display: flex;
    align-items: center;
    }
    .vrow{
        margin-left: 60px;
    }  
</style>